package benny_driving_ser.dao.impl;

/**
 * 新计价器后台逻辑
 */
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import benny_driving_ser.ObjectBean.PayCodeBean;
import benny_driving_ser.ObjectBean.TaximeterDataBean;
import benny_driving_ser.dao.PayCodeDao;
import benny_driving_ser.dao.TaximeterDataSubmitDao;
import benny_driving_ser.util.CalcPayCodeCostUtil;
import benny_driving_ser.util.DBUtil;
import benny_driving_ser.util.FormatUtil;
import benny_driving_ser.util.SendSMSUtil;

public class TaximeterDataSubmitDaoImpl implements TaximeterDataSubmitDao{
	
//	private static final String SMS_URL = "";
//	private static final String SMS_TM_CONTENT = "http://www.4008200972.com/w/j.php&id="
//			+ SMS_URL;
//	private static final String SMS_BILING_CONTENT = "http://www.4008200972.com/w/p.php&id=";
	
	/**
	 * 临时计价器开始逻辑
	 */
	public long taximeterDataSubmit_start(int dri_id) {
		
		String sql_query_orderid = "select d.id,d.state,h.sjh,u.dh,u.xm " +
				"from t_djpd d,t_hy h,t_user u  " +
				"where d.state = 2 and d.user_id = h.id and d.dri_id = u.id and d.dri_id = ?";
		
		String sql_update_state = "update t_djpd set state = 3,start_time=? where id = ?";
		
		long currentTime = System.currentTimeMillis();
		
		int update_num = 0;
		Connection conn = DBUtil.getInstance().openConnection();
		
		try {
			
			conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			conn.setAutoCommit(false);
			
			System.out.println("计价器开始...");
			
			PreparedStatement pst_query_orderid = conn.prepareStatement(sql_query_orderid);
			pst_query_orderid.setInt(1, dri_id);
			ResultSet rs_query_order_id = pst_query_orderid.executeQuery();
			while(rs_query_order_id.next()){
				
				int orderid = rs_query_order_id.getInt("id");
				String userTel = rs_query_order_id.getString("sjh").trim();
//				String driTel = rs_query_order_id.getString("dh").trim();
//				String driName = rs_query_order_id.getString("xm");
				
				if(!userTel.matches("^[1][3-8]\\d{9}$")){
					System.out.println("手机号不合法...");
				}
				
				PreparedStatement pst_update_state = conn.prepareStatement(sql_update_state);
				pst_update_state.setString(1, FormatUtil.getTimeFormat(currentTime));
				pst_update_state.setInt(2, orderid);
				update_num = pst_update_state.executeUpdate();
				
				conn.commit();
				pst_update_state.close();
				rs_query_order_id.close();
				conn.close();
				
				System.out.println("taximeter start ok");
				System.out.println("userTel:"+userTel);
				System.out.println("当前系统时间为:"+FormatUtil.getTimeFormat(currentTime));
				
				SendSMSUtil.getInstance().sendSMS(userTel,URLEncoder.encode("您好,本次代驾服务已开始计费,感谢您使用邦尼驾驶. ", "gbk"));
				return currentTime ;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		finally {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return currentTime;
	}

	
	/**
	 * 临时计价器结束逻辑
	 */
	public int taximeterDataSubmit(TaximeterDataBean taximeterData,int payCost,String payCode) {
		
		int dri_id = Integer.parseInt(taximeterData.getDri_id().trim());
		
		String sql_query_order = "select d.id,d.state d_state,d.ssfy,h.sjh,d.user_id,d.bonus_cost," +
				"u.dh,u.state u_state,u.username,u.mdid,u.ye   " +
				"from t_user u,t_djpd d,t_hy h " +
				"where d.dri_id = u.id and d.state = 3 and d.user_id = h.id and d.dri_id = ?";
		
		String sql_update_state = "update t_djpd d,t_user u SET u.state = 1 ,d.state = 7 where d.id = ? and u.id = ?";
		
		String sql_update_error = "update t_djpd d,t_user u SET u.state = 2 ,d.state = 7 where d.id = ? and u.id = ?";
		
		Connection conn = DBUtil.getInstance().openConnection();
		try{
			conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			conn.setAutoCommit(false);
			if(dri_id!=0){
				PreparedStatement pst_query_order = conn.prepareStatement(sql_query_order);
				pst_query_order.setInt(1, dri_id);
				ResultSet rs_query_order = pst_query_order.executeQuery();
				
				while(rs_query_order.next()){
					int user_id = rs_query_order.getInt("user_id");
					int d_state = rs_query_order.getInt("d_state");
					int u_state = rs_query_order.getInt("u_state");
					int mdid = rs_query_order.getInt("mdid");
					int orderid = rs_query_order.getInt("id");
					String username = rs_query_order.getString("username");
					System.out.println("driState:"+u_state);
					
					int bonus_cost = rs_query_order.getInt("bonus_cost")==0?0:rs_query_order.getInt("bonus_cost");
					double total = Double.parseDouble(taximeterData.getTotal());
					double tax = FormatUtil.getFormatDouble(2, total* getTax(total));
					double ye = rs_query_order.getDouble("ye");
					System.out.println("ye:"+ye);
					
					String driJobNum = rs_query_order.getString("username");
					String userTel = rs_query_order.getString("sjh").trim();
					String driTel = rs_query_order.getString("dh").trim();
					if(!userTel.matches("^[1][3-8]\\d{9}$") || !driTel.matches("driTel")){
						System.out.println("手机号不合法..");
					}
					System.out.println("ye:"+ye+"tax:"+tax);
					
					System.out.println("-------ye:"+ye+"---payCost:"+payCost+"--tax:"+tax+"-bonus_cost"+bonus_cost+"total:"+((ye-tax+((double)bonus_cost)+((double)payCost))));
					double cal_balance = (ye-tax+((double)bonus_cost)+((double)payCost));
					if(	(ye>tax)
						&& (d_state == 3) 
						&& (u_state==0 || u_state == 2)
						&& (UtilDaoImpl.getInstance().insertDriExpenseCalendar(conn,dri_id, (-tax), 1, orderid,driJobNum))
						&& (UtilDaoImpl.getInstance().insertUserExpenseCalendar(conn,user_id, -total, 1, orderid))
						&& (UtilDaoImpl.getInstance().insertManagerCount(conn, mdid,getManageProfit(tax, mdid)))
						&& (UtilDaoImpl.getInstance().isServerSendOrder(conn, tax, orderid))
						&& (PayCodeDaoImpl.insertPayCode2Order(orderid,payCode.trim(),conn)==1)
						&& (UtilDaoImpl.getInstance().updateOrder(taximeterData,tax,mdid,conn,orderid))
						&& (UtilDaoImpl.getInstance().updateUser(cal_balance,dri_id,conn))
//						&& (UtilDaoImpl.getInstance().updateUser(ye,tax,bonus_cost,dri_id,payCost,conn))
						&& (UtilRandomBonus.insertBonus2Pay(conn,ye,dri_id,bonus_cost,username,orderid)==1)
						){
						
						
						if(u_state == 2){
							PreparedStatement pst_update_error = conn.prepareStatement(sql_update_error);
							pst_update_error.setInt(1, orderid);
							pst_update_error.setInt(2, dri_id);
							pst_update_error.executeUpdate(); 
							pst_update_error.close();
						}else{
							PreparedStatement pst_update_state = conn.prepareStatement(sql_update_state);
							pst_update_state.setInt(1, orderid);
							pst_update_state.setInt(2, dri_id);
							pst_update_state.executeUpdate(); 
							pst_update_state.close();//
						}
						String user_message = "";
						String dri_message = "";
						if(payCode==null||payCode.equals("")){
							user_message = "您好,本次代驾起始里程数为:"+taximeterData.getStartmil().trim()+"公里," +
									"到达里程数为:"+taximeterData.getEndmil().trim()+"公里," +
									"共"+(Integer.parseInt((taximeterData.getEndmil().trim()))-(Integer.parseInt(taximeterData.getStartmil().trim())))+"公里." +
									"等候"+taximeterData.getSowt().trim()+"分钟," +
									"您未使用支付码,应付"+total+"元,感谢您使用";
							dri_message = "本次代驾费用"+ total +"元，实收现金"+(total-payCost)+"元,本次服务扣税"+tax+ "元";
						}else{
							PayCodeDao dao = new PayCodeDaoImpl();
							dao.updatePayCodeState(payCode,conn);
							dao.insertPayCost2Pay(username,payCost,orderid,dri_id,conn,ye);
							
							
//							dao.addPayCodeUseLog(payCodeBean, 0, 2, conn);
							user_message = "您好,本次代驾起始里程数为:"+taximeterData.getStartmil().trim()+"公里," +
									"到达里程数为:"+taximeterData.getEndmil().trim()+"公里," +
									"共"+(Integer.parseInt((taximeterData.getEndmil().trim()))-(Integer.parseInt(taximeterData.getStartmil().trim())))+"公里." +
									"等候"+taximeterData.getSowt().trim()+"分钟," +
									"您已经使用支付码: "+payCode+" ,总共"+total+"元,支付码抵扣"+CalcPayCodeCostUtil.CalcPayCodeCost(payCode, conn)+"元,应付"+(total-payCost)+"元,感谢您使用";
							dri_message = "本次代驾费用"+ total +"元，用户使用电子支付码抵扣"+payCost+"元,实收现金"+(total-payCost)+"元,本次服务扣税"+tax+ "元";
						}
							
						System.out.println(user_message);
						System.out.println(dri_message);
						SendSMSUtil.getInstance().sendSMS(userTel,URLEncoder.encode(user_message, "gbk"));
						SendSMSUtil.getInstance().sendSMS(driTel,URLEncoder.encode(dri_message, "gbk"));
						
						pst_query_order.close();
						rs_query_order.close();
						conn.commit();
						conn.close();
						
						System.out.println("taximeter stop ok");
						return 0;
					}
					conn.rollback();
					conn.close();
					
					System.out.println("数据同步异常...");
					return 1;
				}
			}else{
			System.out.println("订单id为空...");
			conn.rollback();
			conn.close();
			return 1;
			}
			
		}catch(SQLException e){
			System.out.println("sql语句错误");
			e.printStackTrace();
			try {
				conn.rollback();
				conn.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			return 2;
		}
		catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return 1;
	}
	
	private double getTax(double total) {
		if (total < 20)
			return 0; 
		if (total >= 20 && total < 50)
			return 0.1;
		if (total >= 50 && total < 100)
			return 0.15;
		return 0.2;
	}

	private double getManageProfit(double param, int mdid) {
		double mParam = param * 0.04d;
		if (mdid == 7)
			mParam = param * 0.15d;
		return FormatUtil.getFormatDouble(3, mParam);
	}
	
}
